package com.mvu.banana.user.server;

import com.mvu.banana.common.server.AJAXServlet;
import com.mvu.banana.domain.client.Gender;
import com.mvu.banana.domain.server.BlockReturn;
import com.mvu.banana.domain.stub.Profile;
import com.mvu.banana.user.generated.SearchProfileDTO;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

public class SearchProfileServlet extends AJAXServlet<SearchProfileDTO>{
  
  public SearchProfileDTO post(final SearchProfileDTO criteria){
    List<Profile> profiles = new BlockReturn<List<Profile>>() {
      @Override
      public List<Profile> run(EntityManager em) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Profile> criteriaQuery = builder.createQuery(Profile.class);
        Root<Profile> root = criteriaQuery.from(Profile.class);
        List<Predicate> restrictions = new ArrayList<Predicate>();
        if(!criteria.name.isEmpty()){
          Predicate nameRestriction = builder.equal(root.<String>get(Profile.NAME_PROP), criteria.name);
          restrictions.add(nameRestriction);
        }
        if(criteria.gender != null && !Gender.GENDER.equals(criteria.gender)){
          Predicate genderRestriction = builder.equal(root.<Gender>get(Profile.GENDER_PROP), criteria.gender);
          restrictions.add(genderRestriction);
        }
        criteriaQuery.where(builder.and(restrictions.toArray(new Predicate[restrictions.size()])));
        return em.createQuery(criteriaQuery).getResultList();
      }
    }.run();
    //criteria.setResults(profiles);
    return criteria;
  }
}